package com.guanzi.netty.server.handler;

import com.guanzi.netty.message.GroupChatRequestMessage;
import com.guanzi.netty.message.GroupChatResponseMessage;
import com.guanzi.netty.message.Message;
import com.guanzi.netty.server.session.GroupSession;
import com.guanzi.netty.server.session.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;

@ChannelHandler.Sharable
public class GroupChatRequestMessageHandler extends SimpleChannelInboundHandler<GroupChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupChatRequestMessage msg) throws Exception {
        String content = msg.getContent();
        String groupName = msg.getGroupName();
        String from = msg.getFrom();

        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        List<Channel> channelList = groupSession.getMembersChannel(groupName);

        channelList.forEach(item -> {
            item.writeAndFlush(new GroupChatResponseMessage(from, content));
        });

    }
}
